import React from "react";
import { inject, observer } from "mobx-react";
import { Spin } from "antd";
import loadjs from "loadjs";

@inject('edcAnalysisDesignerStore', 'routing')
@observer
export default class BoardWidgetEditor extends React.Component {

  constructor (props) {
    super();
    this.state = {
      loaded: false,
      appid: props.location.query.appid
    };
    this.store = props.edcAnalysisDesignerStore;
  }

  componentDidMount() {
    this.loadEdcBoard();
  }

  loadEdcBoard() {
    if (loadjs.isDefined('weaEdcBoard')) {
      this.setState({ loaded: true });
      return;
    }

    const libUrl = '/spa/edc/static4engine/board4com/';

    loadjs([
      `${libUrl}index.css`,
      `${libUrl}index.js`,
      '/font/edc/board/iconfont.js',
      '/mobilemode/js/echarts4/echarts.min.js'
    ], 'weaEdcBoard', {
      success: () => {
        const appid = this.state.appid || this.getAppID();

        if (!appid) return;

        this.store.init(appid);
        this.setState({ loaded: true });
      }
    });
  }

  getAppID = () => {
    const routeId = this.props.routeParams.id;
    const routeObj = JSON.parse(this.decode(routeId));
    return routeObj.appid;
  }

  decode = (base64Str) => {
    if (window.atob) {
      return window.atob(base64Str);
    }
    return base64Str.split('')
      .map(ch => ch.charCodeAt() >> 1)
      .map(code => String.fromCharCode(code))
      .join('');
  };

  render() {
    if (!window.weaEdcBoard) return null;

    const { board } = this.store;
    const { BoardWidgetEditor } = window.weaEdcBoard.com;
    const { params } = this.props;
    const isEdit = 'edit' === params.actionType;
    const { loaded } = this.state;

    if (!board && !isEdit) return null;

    if (!loaded) {
      return (
        <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@v4bt2s`} spining={!loaded} style={{ width: '100%', paddingTop: 200 }} />
      );
    }

    return (
      <BoardWidgetEditor ecId={`${this && this.props && this.props.ecId || ''}_BoardWidgetEditor@za03ab`}
        disableDataModelChange={true}
        defaultDataModelIds={isEdit ? '' : board.dataModelIds.split(',')}
        params={params}
      />
    );
  }
}